<!DOCTYPE HTML>
<html>
	<head>
		<link href="ace/style.css" rel="stylesheet" type="text/css">
		<title>Hello World</title>
	</head>

	<body>
		<div id="header">
			<div id="htext">
				Editing <b>hello</b>
				<button class="format-btn" data-attr="bold">Bold</button>
				<button class="format-btn" data-attr="italic">Italic</button>
			</div>
		</div>

		<div id="editor"></div>

		<script src="/lib/ace/ace.js" type="text/javascript" charset="utf-8"></script>
		<script src="/lib/ace/mode-latex.js" type="text/javascript" charset="utf-8"></script>
    <script src="/channel/bcsocket.js"></script>
		<script src="/share/AttributePool.js"></script>
		<script src="/share/Changeset.js"></script>
		<script src="/share/share.uncompressed.js"></script>
		<script src="/share/ace.js"></script>

		<script>
var editor = ace.edit("editor");
editor.getSession().setMode(new (require("ace/mode/latex").Mode));
ed = editor.getSession();

sharejs.open('hello', 'etherpad', function(error, doc) {
	if (doc.created) {
		doc.insert(0, "Hello \\latex world\nLine 2");
		doc.setAttributes(0, 5, [["bold", true]]);
	}

	getOffsetPosition = function(range) {
    	var i, line, lines, offset, _i, _len;
    	lines = ed.getLines(0, range.row);
    	offset = 0;
    	for (i = _i = 0, _len = lines.length; _i < _len; i = ++_i) {
      		line = lines[i];
      		offset += i < range.row ? line.length : range.column;
    	}
    	return offset + range.row;
  	};

  	var buttons = document.getElementsByClassName("format-btn");

  	for(var i = 0; i < buttons.length; i++) {
  		buttons[i].onclick = function (e) {
			range = editor.getSelectionRange();
			if (range.isEmpty())
				return;
			offset = getOffsetPosition(range.start);
			offsetEnd = getOffsetPosition(range.end);

			var btn = e.target;
			doc.setAttributes(offset, offsetEnd-offset, [[btn.dataset.attr, true]]);
		};
  	}

	doc.attach_ace(editor);
});
		</script>
	</body>
</html>	

